// pages/myNian/payCard/payCard.js
var common = require("../../../public.js");
var commonTime = require('../../../utils/peopleList.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        payClick:false,
        currentIndex: 0,
        current: 0,
        isOverShare: true,  //全局分享标识请勿删除
        nianList: [],
        colors: '',
        obj: {}, //年刊详情
        detaiList: [],
        show: false,
        values: '',
        showss: true,
        pagecount: 1,
        totalArr: [], //分页总数据
        qrcodeid: "",
        cardId: "",
        distributorId: '', //支付和激活需要的
        myCardList: [],
        userId: '', //邀请人id
        swiperList: [],
        zhongPhone: '',
        zhongName: '',
        zhongTime: '',
        numLoop:4,
        arr:['','']
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    click_detail(e) {
        let item = e.currentTarget.dataset.item
        if (item.redirectUrl) {
            wx.navigateTo({
                url: '/packageA/pages/Goods/details/index?id=' + item.redirectUrl,
            })
        } else {
            wx.navigateTo({
                url: item.redirectPath,
            })
        }

    },
    // 获取未购买会员卡列表
    reLists() {
        var that = this
        common.get('/userAnnualCard/getCardInfoById', {
            cardId: this.data.cardId
        }, res => {
            if (res.status === 200) {
                that.setData({
                    obj: res.data
                }, () => {
                    // console.log(that.data.obj.managerId,"54444555")
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    onChange(event) {
        this.setData({
            values: event.detail
        })
    },
    ji_huo() {
        var that = this
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    show: true
                })
            } else {
                common.showLoginPage()
            }
        })
    },
    // 激活碼
    fn() {
        var that = this
        var temp = {
            distributorId: that.data.distributorId,
            cardId: that.data.cardId,
            userId: that.data.userInfo.id,
            code: that.data.values,
            token: that.data.token
        }
        common.get('/userAnnualCard/buyAnnualCard/activationCode', temp, res => {
            if (res.status === 200) {

                // 登录已超时，请重新登录
                if (res.msg == "登录已超时，请重新登录") {
                    common.showLoginPage()
                    return
                }
                wx.showToast({
                    title: res.data,
                    duration: 3000, //显示时长
                    icon: 'none',
                    success: function () {
                        that.cardsList()
                    }
                })
            } else {
                common.showRequestErrMsg(res)

            }
        }, () => {
            that.setData({
                values: ''
            })
        })
    },
    getUserInfo(event) {
        this.setData({
            show: false
        },
            () => {
                this.fn()
            })
    },
    closeTap() {
        this.setData({
            show: false
        })
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    // 会员卡详情下面的列表
    cardsList_two(id) {
        var that = this
        common.get('/userAnnualCard/getCardProductListForApplets', {
            cardId: id,
            productType: "",
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            if (res.status === 200) {
                if (id == 7) {
                    var itemss = {
                        discount: 0, //免费
                        frequency: 1,
                        surplusUse: 1,
                        productName: "中国移动咪咕视频会员(联系客服)",
                        originalPrice: 180,
                        idsFlag: 2
                    }
                    res.data.unshift(itemss)
                }
                var newArr = res.data.map((item, index, arr) => {

                    // 进行判断
                    if (!item.cardProductType) {

                        return item
                    } else {
                        item.statusNames = '购买'
                        return item
                    }
                })
                that.setData({
                    nianList: newArr
                })

            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 查看更多  
    click_data() {
        var pageCount = this.data.pagecount + 1
        if (this.data.totalArr.length == pageCount) {
            this.setData({
                showss: false
            })
        }
        if (this.data.totalArr[pageCount - 1]) {
            this.setData({
                detaiList: [...this.data.detaiList, ...this.data.totalArr[pageCount - 1]],
                pagecount: pageCount,
            })
        }
    },

    click_shou() {
        this.setData({
            detaiList: this.data.totalArr[0],
            showss: true,
            pagecount: 1,
        })
    },
    //   去支付 
    go_pay() {
        var that = this
        wx.showLoading({
            title: '正在调起支付',
          })
        if(that.data.payClick == true){

            console.log('禁止连续点击');
            return;
        }
        that.data.payClick = true;
      
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                let tempJson = {
                    cardId: that.data.cardId,
                    openid: that.data.openid,
                    token: that.data.token,
                    userId: that.data.userInfo.id,
                    inviteeId: that.data.userId, //邀请人id
                    distributorId: that.data.distributorId
                }
                // 原来 /chinaumsPayForAnnualCardFYPlatform
                common.wxPayRequest("/wxxcxPayForAnnualCard", tempJson, function (res) {
                    console.log('res状态+----', res)
                    if (res.status == 200) {

                        wx.requestPayment({
                            'timeStamp': res.data.timeStamp,
                            'nonceStr': res.data.nonceStr,
                            'package': res.data.package,
                            'signType': res.data.signType,
                            'paySign': res.data.paySign,
                            'success': function (res) {
                                common.showToast('支付成功', 'success')
                                that.cardsList()
                            },
                            'fail': function (res) {
                                console.log("222334",res)
                                if (res.errMsg === 'requestPayment:fail cancel') {

                                } else {
                                    common.showToast(res.errMsg)
                                }
                            }
                        })
                        setTimeout(function () {
                            wx.hideLoading()
                            console.log('调起');
                            that.data.payClick = false;
                        //要延时执行的代码
                        }, 2000) //延迟时间 这里是2秒

                        if (res.msg == "登录已超时，请重新登录") {
                            common.showLoginPage()
                            return
                        }
                        if (res.status == 400) {
                            wx.showToast({
                                title: res.msg,
                                duration: 3000, //显示时长
                                icon: 'none',
                                success: function () {
                                    that.cardsList()
                                }, //接口调用成功
                            })
                            return
                        }

                    }else{
                        that.data.payClick = false;
                        common.showRequestErrMsg(res)
                    }
                    
                })




            } else {
                wx.hideLoading()

                that.data.payClick = false;
                console.log("没有登录")
                common.showLoginPage()
            }
        })

    },
    // 获取未购买会员卡列表
    getAdvertiser() {
        var that = this
        common.post('/advertisements/searchAdvertisementByCardId', {
            cardId: that.data.cardId
        }, res => {
            if (res.status === 200) {
                that.setData({
                    swiperList: res.data
                }, () => {
                    // console.log(that.data.obj.managerId,"54444555")
                })
            } else {
                // common.showRequestErrMsg(res)
            }
        })
    },
    Ranmdomss() {
        let one = Math.floor(Math.random() * 99);
        let two = Math.floor(Math.random() * 49);
        let three = Math.floor(Math.random() * 29);
        this.setData({
            zhongName: commonTime.nameList[one] + '**',
            zhongPhone: commonTime.phoneList[two],
            zhongTime: commonTime.timeList[three]
        })

    },
    RandomFn(e) {
        this.Ranmdomss()
   
        // this.setData({
        //     current:e.detail.current
        // })
       
        //   console.log(e.detail.current)
        //   if (this.data.current == 0 && this.data.currentIndex > 1) { //卡死时，重置current为正确索引
        //     this.setData({
        //         current: this.data.currentIndex
        //     });
        // } else { //正常轮转时，记录正确页码索引
        //     this.setData({
        //         currentIndex: e.detail.current
        //     });
        // }
    },
    onLoad: function (opt) {
        console.log(opt, "jjjj445555dvfhgdfhu")
        var that = this
        //获取胶囊位置
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        var windowHeight = wx.getSystemInfoSync().windowHeight
        var windowWidth = wx.getSystemInfoSync().windowWidth
        this.setData({
            scroll_height: windowHeight * 750 / windowWidth - 200
        })
        if (opt.q) {
            let scan_url = decodeURIComponent(opt.q);
            console.log('哈哈哈哈--',scan_url);
          
            let video_id = scan_url.match(/\d+/) //提取链接中的数字，也就是链接中的参数id，/\d+/ 为正则表达式
            var distributorId = video_id['input'].split("=")
            console.log('aaaaa--',video_id,'---bbbb---',distributorId);
            common.getLocalUserInfo(function (success, data) {
                if (success) {
                    console.log(data,"2222")
                    that.setData({
                        userInfo: data.user,
                        token: data.token,
                        openid: data.openid,
                        cardId: video_id[0],
                        distributorId: distributorId[3] ? distributorId[3] : ''
                    }, function () {
                        this.reLists() //获取这张会员卡的信息
                        that.cardsList_two(that.data.cardId) //这张会员卡下面的权益
                        this.isPay()
                        that.getAdvertiser()

                    })
                } else {
                    common.showLoginPage()
                }
            })
            return
            //  公眾號
        } else {
            common.getLocalUserInfo(function (success, data) {
                console.log(data)
                if (success) {
                    that.setData({
                        userInfo: data.user,
                        token: data.token,
                        openid: data.openid,
                        cardId: opt.cardId ? opt.cardId : 86,
                        distributorId: opt.distributorId ? opt.distributorId : '',
                        userId: opt.userId ? opt.userId : '' //分享页面分享邀请人id
                    }, function () {
                        this.reLists()
                        that.cardsList_two(that.data.cardId) //这张会员卡下面的权益
                        this.isPay()
                        that.getAdvertiser()
                        this.Ranmdomss()

                    })
                } else {
                    common.showLoginPage()
                }
            })
        }
    },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    // 我购买会员卡列表接口-------------------------------------------------------------------------------
    cardsList() {
        var that = this
        common.get('/userAnnualCard/getUserCardProductList', {
            userId: that.data.userInfo.id,
            token: that.data.token
        }, res => {
            if (res.status === 200) {
                console.log(res.data, "myCardList")
                let cardList = res.data
                var item = cardList.find((items) => {
                    return items.annualCardId == that.data.cardId
                })

                console.log(item,'6666666666666666666666888888888888')
                setTimeout(() => {

                    var obj = JSON.stringify(item)
                    wx.navigateTo({
                        url: '/packageA/pages/indexnian/indexni?obj=' + encodeURIComponent(obj),
                    })
                }, 1000)

            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 判断是否支付
    isPay() {
        var that = this
        common.get('/userAnnualCard/checkUserBoughtCard', {
            userId: this.data.userInfo.id,
            cardId: this.data.cardId,
            token: this.data.token
        }, res => {
            console.log(res)
            if (res.status === 1) {
                common.showToast(res.msg)
                that.cardsList()
            }
        })
    },
    // 跳转会员卡协议
    click_cie() {
        wx.navigateTo({
            url: '/packageB/pages/agreement/agreement',
        })
    },
    onShareAppMessage: function () {
        return {
            title: this.data.title,
            path: '/pages/myNian/payCard/payCard?cardId=' + this.data.cardId + '&distributorId=' + this.data.distributorId,
            // imageUrl: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/yearCard/year_cardshare.jpg',

            success: (res) => {
                // 分享成功
            },
            fail: (res) => {
                // 分享失败
            }
        }
    },
})